// 注册页
import React from 'react'
import './index.css'
import Logo from '../../images/logo.png'
import Foot from '../Public/Footer.jsx'
import {Link} from 'react-router-dom'
import {connect} from 'react-redux'
import {getUsers,setUsers} from '../../store/Register.redux'
@connect(
	state=>({
		users:state.Register.users
	}),{
		getUsers,setUsers
	}
)
class Register extends React.Component{
    constructor(props){
        super(props)
        this.state={
			tel:'', 			//手机号
			code:'',			//验证码
			setPassword:'', 	//创建时的密码
			affirmPassword:'',	//确认时的密码
			staus:false          //默认用户账号不存在状态
		}
	}
	// 失焦时设置tel
	setTleVlue=(tell)=>{
		this.setState({
			tel:this.refs.tel.value
		},()=>{
			//请求数据库查看是否账号存在回馈
			this.props.getUsers(tell);	
		})	
	}
	componentWillReceiveProps(props){
		if(props.users.length!=0){
			alert('用户已存在，点击确定立即进入登录页');
			//用户存在时改变状态
			this.setState({
				staus:true
			})
			this.props.history.push({pathname:'/login'})//跳转到登录页
		}
	}
	// 失焦时设置验证码
	setCode=(e)=>{
		this.setState({
			code:e.target.value
		})
	}
	// 失焦时设置password1
	setPass=(e)=>{
		this.setState({
			setPassword:e.target.value
		})
	}
	// 失焦时设置password2
	setPassW=(e)=>{
		this.setState({
			affirmPassword:e.target.value
		})
	}
	// 点击注册按钮时方法
	submit=(use,passwor)=>{
		// 先判断用户账号不为空的情况下
		let tel = this.state.tel
		if(tel !== ''){
			// 判断状态
			let status = this.state.staus
			if(status!==true){
				// 判断两个密码是否相等
				let pass1 = this.state.setPassword
				let pass2 = this.state.affirmPassword
				if(pass1===pass2){
						// 将账号数据写入到数据库中
						this.props.setUsers(use,passwor)
						alert('注册成功')
				}else{
					alert('密码不相同，请从新输入')
				}
			}else{
				alert('用户账号已存在，请直接登录')
			}
		}else{
			alert('请输入手机号')
		}
		
	}
    render(){
        return (
			<div>
            <div className="content">
				<div className="log">
					<img src={Logo} alt=''/>
					<span>欢迎注册</span>
				</div>
				<div className="cont">
				<div className="formLeft">
					<form>
						<h3>注册</h3>
						手机号码：<input type="tel" ref="tel" name="users" onBlur={()=>this.setTleVlue(this.state.tel)} placeholder="请输入手机号码"/><br />
						&nbsp;&nbsp;&nbsp;验证码：<input type="text" name="text" onBlur={this.setCode} placeholder="输入验证码"/><button>验证码</button><br />
						创建密码：<input type="password" name="pass" onBlur={this.setPass} placeholder="输入6-16位字母或数字密码"/><br />
						确认密码：<input type="password" name="password"  onBlur={this.setPassW} placeholder="再次输入密码"/><br />
						<button type="button" className="width" onClick={()=>this.submit(this.state.tel,this.state.affirmPassword)}>注册</button>
					</form>
				</div>
				<div className="formRight">
					<div className="formRightCont">
					<span className="spanBlock">已经注册过 ？</span>
					<span className="spanBlock">请点击 <Link to='/login'>直接登录 </Link></span>
					</div>
				</div>
			</div>
		</div>
		<Foot></Foot>
		</div>
        )
    }

}
export default Register